<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <meta name="format-detection" content="telephone=no"/>
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <title></title>
    <script type="text/javascript" src="../../script/jquery.min.js"></script>
    <script type="text/javascript" src="../../script/permission.js"></script>
    <script type="text/javascript" src="../../script/resize.js"></script>
    <script type="text/javascript" src="../../script/requestTool.js"></script>
    <script type="text/javascript" src="../../script/api.js"></script>
    <script type="text/javascript" src="http://img.cfnet.org.cn/tools/layer/v3.1.1/layer.js"></script>
    <script src="../../script/mui.min.js" type="text/javascript"></script>
    <script src="../../script/mui.zoom.js" type="text/javascript"></script>
    <script src="../../script/mui.zoom.js" type="text/javascript"></script>
    <script src="../../script/mui.previewimage.js" type="text/javascript"></script>
    <script src="../../script/chat/ui_chat.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="../../css/mui.min.css">
    <link rel="stylesheet" type="text/css" href="http://cjrh.cfnet.org.cn/custom/css/base.css">
    <link rel="stylesheet" type="text/css" href="../../css/chat.css">
    <script src="../../script/chat/tinymce/tinymce.min.js"></script>
    <script src="../../script/chat/ring_timer_task.js"></script>
    <script src="../../script/chat/chatDB.js"></script>
    <style>
        .emoji {
            height: 0.4rem;
            width: 1px;
            margin-top: 0.1rem;
            display: inline-block;
            /*padding: ;*/
        }

        .msg-img {
            display: none;
        }
    </style>
    <script>

    </script>
    <style>
        #msg-text {
            -webkit-user-select: text;
            border-radius: 3px;
            outline: 0;
            /*   background-color:#000000;*/
            -webkit-appearance: none;
        }

        body {
            -webkit-user-select: all
        }
    </style>
</head>
<body>
<div class="allwrap">
    <div class="chatwrap">
        <!--下拉刷新容器-->
        <div id="pullrefresh" class="mui-scroll-wrapper" data-scroll="1">
            <!--            <div>-->
            <!--数据列表-->
            <div class="mui-scroll" id="msgsList">
            </div>
            <!--            </div>-->
        </div>
    </div>
    <!-- 底部 -->
    <div class="chatbotwrap">
        <div class="chatbot-top">
            <div class="chatbtncont">
                <span class="chat-btn chat-audio"><img src="../../image/chat/chat03.png" alt=""></span>
                <span class="chat-btn chat-left-key hide"><img src="../../image/chat/chat04.png" alt=""></span>
                <div class="chat-input ">
                    <input type="text" id="msg-text"
                           style="font-size: 0.3rem;line-height: 0.3rem;"
                           class="keyinput"/>
                    <button style="background: none;color: black" id="msg-sound" class="mui-input-speech audioinput">按住
                        说话
                    </button>
                </div>
                <span class="chat-btn chat-emoji"><img src="../../image/chat/chat01.png" alt=""></span>
                <span id="right-key" class="chat-btn chat-right-key hide"><img src="../../image/chat/chat04.png" alt=""></span>
                <span id="btnOther" class="chat-btn chat-add"><img src="../../image/chat/chat02.png" alt=""></span>
                <button id="btnTextSend" onclick="sendText()"
                        style="vertical-align:middle;height:.44rem;width: 1rem;background: #ff2d4a;border-radius: 0.1rem;color: white;margin: 0.1rem">
                    发送
                </button>
            </div>
        </div>
        <div class="chatbot-bot">
            <div class="chataddcont">
                <span><img onclick="selectedImg()" src="../../image/chat/chat05.png" alt="图片"></span>
                <span id="select_file"><img onclick="selecteFile()" src="../../image/chat/chat06.png" alt="文件"></span>
            </div>
            <!-- emoji -->
            <div class="chatemojicont">
                <img src="../../image/chat/emoji/aini.png" onclick="appendText('[:A)]')" class="img-emoji">
                <img src="../../image/chat/emoji/bishi.png" onclick="appendText('[:B)]')" class="img-emoji">
                <img src="../../image/chat/emoji/bizui.png" onclick="appendText('[:C)]')" class="img-emoji">
                <img src="../../image/chat/emoji/bulini.png" onclick="appendText('[:D)]')" class="img-emoji">
                <img src="../../image/chat/emoji/daku.png" onclick="appendText('[:E)]')" class="img-emoji">
                <img src="../../image/chat/emoji/deyi.png" onclick="appendText('[:F)]')" class="img-emoji">
                <img src="../../image/chat/emoji/gaxiao.png" onclick="appendText('[:G)]')" class="img-emoji">
                <img src="../../image/chat/emoji/jiaxiao.png" onclick="appendText('[:H)]')" class="img-emoji">
                <img src="../../image/chat/emoji/kaixin.png" onclick="appendText('[:I)]')" class="img-emoji">
                <img src="../../image/chat/emoji/keai.png" onclick="appendText('[:J)]')" class="img-emoji">
                <img src="../../image/chat/emoji/liuhan.png" onclick="appendText('[:K)]')" class="img-emoji">
                <img src="../../image/chat/emoji/liuhan_1.png" onclick="appendText('[:L)]')" class="img-emoji">
                <img src="../../image/chat/emoji/nanguo.png" onclick="appendText('[:M)]')" class="img-emoji">
                <img src="../../image/chat/emoji/nanshou.png" onclick="appendText('[:N)]')" class="img-emoji">
                <img src="../../image/chat/emoji/se.png" onclick="appendText('[:O)]')" class="img-emoji">
                <img src="../../image/chat/emoji/weixiao.png" onclick="appendText('[:P)]')" class="img-emoji">
                <img src="../../image/chat/emoji/xiaoku.png" onclick="appendText('[:Q)]')" class="img-emoji">
                <img src="../../image/chat/emoji/xiudaliao.png" onclick="appendText('[:R)]')" class="img-emoji">
                <img src="../../image/chat/emoji/yukuai.png" onclick="appendText('[:S)]')" class="img-emoji">
                <img src="../../image/chat/emoji/zhiqi.png" onclick="appendText('[:T)]')" class="img-emoji">
            </div>
        </div>
    </div>
</div>
<!-- 浮动话筒 -->
<div class="fixsound" id="sound-alert">
    <!-- sound-icon上加lev1,lev2,lev3,lev4,lev5,lev6,lev7切换7个音量等级 -->
    <div class="sound-icon">
        <img src="../../image/chat/chat07.png" alt="话筒">
        <i></i>
    </div>
    <p id="audio_tips" class="sound-txt">手指上划，取消发送</p>
</div>
<input id="input_clipper" value="" style="z-index: -1;position: fixed" readonly/>
<script>
    var easeChat;
    var conversationId;
    var myRingName;//我的环信用户名
    var conversationPeopleList;
    var startMsgId = '';
    var isScrollBottom;
    var audioRecorder;
    var audioPath;
    var insertList = [];
    // var scroll = mui('.mui-scroll-wrapper').scroll();
    apiready = function () {
        initDB();
        conversationId = api.pageParam.conversationId;
        conversationPeopleList = api.pageParam.conversationPeopleList;
        if (!api.pageParam.effective_state) {
            //已过期
            $('.chatbotwrap').hide();
            $('.allwrap').css('padding-bottom', 0);
        }
        // if (api.systemType === 'ios')
        $('#select_file').hide();
        openTimer();//打开定时任务
        myRingName = $api.getStorage('cfnetringid');//我的环信id
        audioRecorder = api.require('audioRecorder');

        easeChat = api.require('easeChat');
        //新消息接收
        api.addEventListener({
            name: 'ringmessage'
        }, function (ret, err) {
            updatetagRead(ret.value.message[ret.value.message.length - 1].messageId);
            addData(false, ret.value.message)
        });
        //@某人
        api.addEventListener({
            name: 'selectPeopleFinish'
        }, function (ret, err) {
            var temp = $("#msg-text").val();
            insertList.push({nickname: "@" + ret.value.people.nickname + " ", id: ret.value.people.username});//插入@某人的位置
            currentContent = temp.slice(0, cursorPos) + ret.value.people.nickname + " " + temp.slice(cursorPos, temp.length);
            $("#msg-text").val(currentContent);

        });
        loadHistory(true);
    };
    mui.plusReady(function () {
        alert("dsa");
    });
    mui.init({
        gestureConfig: {
            longtap: true, //默认为false。长按屏幕
            hold: true, //默认为false，不监听。 按住屏幕
            drag: true, //默认为true 拖动中
            release: true //默认为false，不监听。  离开屏幕
        },
        pullRefresh: {
            container: '#pullrefresh',
            down: {
                style: 'circle',
                callback: pulldownRefresh
            }
        }
    });
    //关闭图片预览
    $("body").on("click touchstart", ".mui-preview-close", function () {
        mui.previewImage().close();
    });

    function updatetagRead(messageId) {
        cfnetppPOST(url_ring_tagRead, {
            uid: myRingName,
            group_id: conversationId,
            msg_id: messageId
        }, false, function () {

        });
    }

    function getUserName(fromId) {
        var name = fromId;
        for (var i = 0; i < conversationPeopleList.length; i++) {
            if (conversationPeopleList[i].username === fromId) {
                name = conversationPeopleList[i].nickname;
                break;
            }
        }
        return name;
    }

    function addData(isBefore, messages) {
        //添加数据
        for (var i = 0; i < messages.length; i++) {
            var item = undefined;
            if (messages[i].conversationId !== conversationId)
                continue;
            switch (messages[i].body.type) {
                case "text":
                    item = createTextMsg({
                        name: getUserName(messages[i].from),
                        icon: "../../image/chat/p03.png",
                        tags: parseTag(messages[i].from)
                    }, messages[i], messages[i].from === myRingName);
                    break;
                case "image"://图片s
                    item = createImgMsg({
                        name: getUserName(messages[i].from),
                        icon: "../../image/chat/p03.png",
                        tags: parseTag(messages[i].from)
                    }, messages[i], messages[i].from === myRingName);
                    break;//text：文本类型
                case "voice"://语音
                    item = createVoiceMsg({
                        name: getUserName(messages[i].from),
                        icon: "../../image/chat/p03.png",
                        tags: parseTag(messages[i].from)
                    }, messages[i], messages[i].from === myRingName);
                    break;
                case "video"://视频
                    item = createVideoMsg({
                        name: getUserName(messages[i].from),
                        icon: "../../image/chat/p03.png",
                        tags: parseTag(messages[i].from)
                    }, messages[i], messages[i].from === myRingName);
                    break;
                case "file"://文件a
                    item = createFileMsg({
                        name: getUserName(messages[i].from),
                        icon: "../../image/chat/p03.png",
                        tags: parseTag(messages[i].from)
                    }, messages[i], messages[i].from === myRingName);
                    break;

            }
            if (item === undefined)
                continue;
            if (isBefore)
                $('#msgsList').prepend(item);
            else
                $('#msgsList').append(item);
            if (isScrollBottom) {
                mui('.mui-scroll-wrapper').scroll().reLayout();
                mui('.mui-scroll-wrapper').scroll().scrollToBottom(100);//100毫秒滚动到底部
            }
            // if (!messages[i].isRead) {
            //     markMessage(messages[i].messageId);
            // }

        }
        markMessage()
    }

    /**
     * 下拉刷新具体业务实现
     */
    function pulldownRefresh() {
        loadHistory(false);

    }

    //获取历史数据
    function loadHistory(isInit) {
        cfnetppPOST(url_ring_history,{
            "group_id":conversationId,
            "msg_id":startMsgId,
            "rows":50
        }, false, function (data, err) {
            mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
            if (data.status) {
                if (data.data.list.length > 0) {
                    addData(true, data.data.list);
                    if (isInit)
                        updatetagRead(data.data.list[0].messageId);
                    if (startMsgId.length <= 0) {
                        setTimeout(function () {
                            // mui('#pullrefresh').pullRefresh().setStopped(false);
                            mui('.mui-scroll-wrapper').scroll().reLayout();
                            mui('.mui-scroll-wrapper').scroll().scrollToBottom(100);//100毫秒滚动到底部
                            mui('#pullrefresh').pullRefresh().refresh(true);
                            // mui.trigger($('.chat-left-key'),'tap');
                            // mui('#pullrefresh').pullRefresh().setStopped(false);

                        }, 1000);
                    }
                    startMsgId = data.data.list[data.data.list.length - 1].messageId;
                }
            }
        });
        // easeChat.loadMessageFromDB({
        //     conversationId: conversationId,
        //     type: 'groupChat',/
        //     startMsgId: startMsgId
        // }, function (ret) {
        //     if (ret.messages.length > 0)
        //         startMsgId = ret.messages[ret.messages.length - 1].messageId;
        //     addData(true, ret.messages.sort(function (a, b) {
        //         return b.timestamp - a.timestamp;
        //     }));
        // });
    }

    function imgattr() {
        var imglist = mui(".mentor-msg-txt>img");
        $.each(imglist, function (index, el) {
            $(el).attr({
                'data-preview-src': '',
                'data-preview-group': '1'
            });
        });
    }

    window.onload = function () {
        mui.previewImage();
        $('#btnTextSend').hide();
        mui('.mui-table-view').on('tap', '.img-style', function () {
            //mui.previewImage();//调用函数
            console.log("das");
        })
    };

    //语音js开始
    var MIN_SOUND_TIME = 800;
    var recordCancel = false;
    var recorder = null;
    var startTimestamp = -1;
    var stopTimestamp = null;
    var stopTimer = null;

    var audio_tips = document.getElementById("audio_tips");
    var soundAlert = document.getElementById("sound-alert");

    // 控制录音弹出框是否播放
    var setSoundAlertVisable = function (show) {
        if (show) {
            soundAlert.style.display = 'block';
            soundAlert.style.opacity = 1;
        } else {
            $('#sound-alert .sound-icon').removeClass().addClass('sound-icon');
            soundAlert.style.opacity = 0;
            //  完成再真正隐藏
            setTimeout(function () {
                soundAlert.style.display = 'none';
            }, 200);
        }
    };
    var cursorPos = 0;//记录光标位置
    var currentContent = "";//当前内容
    document.getElementById("msg-text").addEventListener('input', function () {
        //是否是新增字符且最后一个字符为@符号
        cursorPos = getCursor(this);
        if (this.value.length === currentContent.length)
            return;
        if (this.value.length > currentContent.length) {
            //增加内容
            if (this.value.charAt(cursorPos - 1).match('@')) {
                api.sendEvent({
                    name: 'selectPeople'
                });
            }
        } else {
            //更新
            // var changeContent = currentContent.slice(cursorPos, cursorPos + currentContent.length - this.value.length);
            // if (changeContent.match(" ")) {
            //     for (var i = 0; i < insertList.length; i++) {
            //         if (insertList[i].nickname.match(this.value.slice(cursorPos - insertList[i].nickname.length, cursorPos))) {
            //             //移除用户
            //             var str1 = this.value.slice(0, cursorPos - insertList[i].nickname.length);
            //             var str2 = this.value.slice(cursorPos, currentContent.length);
            //             $('#msg-text').val(str1 + str2);
            //             this.setSelectionRange(str1.length, str1.length);
            //         }
            //     }
            //
            // }
        }
        currentContent = this.value;
    });

    function updateState() {

    }

    //获取焦点位置
    function getCursor(elem) {
        //IE 9 ，10，其他浏览器
        if (elem.selectionStart !== undefined) {
            return elem.selectionStart;
        } else { //IE 6,7,8
            var range = document.selection.createRange();
            range.moveStart("character", -elem.value.length);
            var len = range.text.length;
            return len;
        }
    }
    var isHold;
    var isVoiceArea;//是否在录音区域
    // mui.plusReady(function(){
    //     console.log("dsa");
    /**
     * 录制语音文件转base64字符串
     */
    // 按住录音（长按开始录音）
    document.querySelector('#msg-sound').addEventListener('hold', function () {
        recordCancel = false;
        //如果有结束时间，清除定时器
        // if (stopTimer) {
        // stopTimer=null;
        // }
        var resultList = api.hasPermission({
            list: ['microphone']
        });
        if (resultList[0].granted) {
            //修改显示文字
            audio_tips.innerHTML = "手指上划，取消发送";

            //话筒弹出框显示出来
            setSoundAlertVisable(true);
            //仅震动
            api.notification({
                vibrate: [0, 100]
            });


            isHold=true;
            var format=api.systemType === 'ios'?'aac':'amr';
            audioPath = api.fsDir + "/cache/audio/" + Date.parse(new Date()) + ".aac";
            audioRecorder.startRecord({
                savePath: audioPath,
                channel:1,
                sampleRates:8000,
                format: 'aac'
            }, function (ret, err) {
                if (ret.status) {
                    openVoiceListener();
                }
            });
            // api.startRecord({
            //     path: "fs://cache/audio/" + Date.parse(new Date()) + ".amr"
            // });
            //记录当前录音时间
        } else {
            checkPermission(['microphone'], function (ret) {
                if (!ret) {
                    api.toast({
                        msg: '无法获录音权限',
                    });
                }
            });
        }
    }, false);
    // 释放保存（松手保存）
    document.querySelector('#msg-sound').addEventListener('release', function (event) {
        isHold=false;
        isVoiceArea=!(Math.abs(event.detail.deltaY) > 50);
    }, false);

    function openVoiceListener() {
        startTimestamp = (new Date()).getTime();
        stopTimer = setInterval(function () {
            if(!isHold){
                setSoundAlertVisable(false);
                clearInterval(stopTimer);
                audioRecorder.stopRecord(function (ret) {
                    if (!ret.status)
                        return;
                    if (audio_tips.classList.contains("cancel")) {
                        audio_tips.classList.remove("cancel");
                        audio_tips.innerHTML = "手指上划，取消发送";
                    }
                    if(!isVoiceArea)
                        return;
                    stopTimestamp = (new Date()).getTime();
                    if (startTimestamp === -1 || stopTimestamp - startTimestamp < 1000) {
                        //录音时间太短
                        startTimestamp = -1;
                        api.toast({"msg":"录音时间太短"});
                        return;
                    }
                    // covertToMp3(audioPath, parseInt((stopTimestamp - startTimestamp) / 1000));
                    sendAudio(audioPath, parseInt((stopTimestamp - startTimestamp) / 1000));
                });
                return;
            }
            audioRecorder.getVolume(function (ret) {
                var level = Math.min(parseInt(ret.volume / 5), 7);
                $('#sound-alert .sound-icon').removeClass().addClass('sound-icon').addClass('lev' + level);
            });
        }, 200);
        // audioRecorder.addEventListener({
        //     name: 'volume'
        // }, function (ret) {
        //     console.log(JSON.stringify(ret));
        //     var level = Math.min(parseInt(ret.volume / 5), 7);
        //     $('#sound-alert .sound-icon').removeClass().addClass('sound-icon').addClass('lev' + level);
        // });
    }
    function covertToMp3(audioPath, time) {
        var converPath=api.fsDir + "/cache/audio/" + Date.parse(new Date()) + ".mp3";
        audioRecorder.covertToMp3({
            originalFilePath: audioPath,
            mp3FilePath: converPath,
            channel:1,
        }, function(ret) {
            if(ret.status){
                sendAudio(converPath, time);
            }
        });

    }
    function updateMessage(message) {
        api.sendEvent({
            name: 'message',
            extra: {
                message: message
            }
        });
    }


    //发送音频
    function sendAudio(audioPath, audioLen) {
        easeChat.sendVoice({
            conversationId: conversationId,
            chatType: "groupChat",
            path: audioPath,
            displayName: audioPath.substring(audioPath.lastIndexOf("/") + 1),
            length: audioLen,
            to: conversationId
        }, function (ret, err) {
            if (ret.status) {
                if (api.systemType === 'ios') {
                    uploadMsgToCFnet(ret.message);
                    addData(false, [ret.message]);
                } else {
                    var displayName = ret.message.body.displayName;
                    var messageId = ret.message.messageId;
                    var sum = 0;
                    var timer = setInterval(function () {
                        easeChat.loadMessageFromDB({
                            conversationId: conversationId,
                            type: 'groupChat',
                            pagesize: 100
                        }, function (ret) {
                            for (var i = 0; i < ret.messages.length; i++) {
                                if (ret.messages[i].body.displayName === displayName && ret.messages[i].body.remotePath.length > 0) {
                                    uploadMsgToCFnet(ret.messages[i]);
                                    addData(false, [ret.messages[i]]);
                                    clearInterval(timer);
                                    return;
                                }
                            }
                            if (++sum === 15) {
                                sendFail("服务器响应超时，您的语音可能发送失败");
                                //发送至全局队列，持续监测该消息状态
                                api.sendEvent({
                                    name: 'audio_fail',
                                    extra: {
                                        conversationId: conversationId,
                                        type: 'groupChat',
                                        messageId: messageId,
                                        displayName: displayName
                                    }
                                });
                                clearInterval(timer);
                            }
                        });
                    }, 200);
                }
            } else {
                sendFail("语音发送失败,请重新发送");
            }
        });
    }

    function appendText(msg) {
        var content = $('#msg-text').val();
        content += msg;
        $('#msg-text').val(content);
        // $('#msg-text').focus();
        // tinyMCE.editors['msg-text'].insertContent(parseEmoji(msg));
    }


    function insertHtmlAtCaret(html) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
                // Range.createContextualFragment() would be useful here but is
                // non-standard and not supported in all browsers (IE9, for one)
                var el = document.createElement("div");
                //el.innerHTML = html;
                el.appendChild(html);
                var frag = document.createDocumentFragment(), node, lastNode;
                while ((node = el.firstChild)) {
                    lastNode = frag.appendChild(node);
                }
                range.insertNode(frag);
                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    range.collapse(true);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if (document.selection && document.selection.type != "Control") {
            // IE < 9
            document.selection.createRange().pasteHTML(html);
        }
    }

    String.prototype.replaceAll = function (a, b) {//吧a替换成b
        var reg = new RegExp(a, "g"); //创建正则RegExp对象
        return this.replace(reg, b);
    };


    //发送文本
    function sendText() {
        var text = $('#msg-text').val();
        var atList = [];
        // var temp=text.match(/@.*[ ]/g);
        // if(temp){
        for (var j = 0; j < insertList.length; j++) {
            if (text.match(insertList[j].nickname)) {
                var id = insertList[j].id;
                atList.push({userName: getUserName(id), userId: id});
                break;
            }
        }
        // }
        insertList = [];//清空内容
        currentContent = "";
        //清空内容
        $('#msg-text').val("");
        easeChat.sendText({
            conversationId: conversationId,
            chatType: "groupChat",
            "text": text,
            ext: {
                "at": atList
            },
            to: conversationId
        }, function (ret, err) {
            if (ret.status) {
                console.log("环信:" + JSON.stringify(ret));
                ret.message.ext.at = atList;//apicloud bug 集合自动变为数组强转掉
                uploadMsgToCFnet(ret.message);
                addData(false, [ret.message]);
                mui('.mui-scroll-wrapper').scroll().reLayout();
                mui('.mui-scroll-wrapper').scroll().scrollToBottom(100);//100毫秒滚动到底部
            } else {
                sendFail("消息发送失败,请重新发送")
            }
        });
    }


    // 监听drag（拖动中）事件（手指上划，取消发送）
    document.body.addEventListener('drag', function (event) {
        if (Math.abs(event.detail.deltaY) > 50) {
            //此时没有录音操作执行 检查recordCancel状态
            if (!recordCancel) {
                recordCancel = true;
                if (!audio_tips.classList.contains("cancel")) {
                    audio_tips.classList.add("cancel");
                }
                audio_tips.innerHTML = "松开手指，取消发送";
            }
        } else {
            if (recordCancel) {
                recordCancel = false;
                if (audio_tips.classList.contains("cancel")) {
                    audio_tips.classList.remove("cancel");
                }
                audio_tips.innerHTML = "手指上划，取消发送";
            }
        }
    }, false);

    mui("#msgsList").on("longtap", ".clipper", function (event) {
        copyToClip(this.innerHTML);
    });
    //切换语音
    mui(".chatbtncont").on("tap", ".chat-audio", function () {
        changeUi('audio');
    });
    //切换键盘
    mui(".chatbtncont").on("tap", ".chat-left-key", function () {
        changeUi('text');
    });
    //切换键盘
    mui(".chatbtncont").on("tap", ".chat-right-key", function () {
        changeUi('text');
    });
    //点击表情
    mui(".chatbtncont").on("tap", ".chat-emoji", function () {
        $('.chat-right-key').removeClass('hide').addClass('show');
        $(this).removeClass('show').addClass('hide');

        //隐藏图片、文件
        $(".chataddcont").removeClass('show');
        //显示表情列表
        $(".chatemojicont").addClass('show');
        $(".chatbot-bot").addClass('show');
        //allwrap改变padding-bottom值
        $(".allwrap").addClass('padmore');
        //打开软键盘
        $('.chatbtncont .chat-audio').removeClass('hide').addClass('show');
        $('#msg-text').show();
        $('.chatbtncont .chat-left-key').removeClass('show').addClass('hide');
        $(".chat-input").find(".audioinput").hide();
    });
    //点击添加图片、文件
    mui(".chatbtncont").on("tap", ".chat-add", function () {
        $(".chatbot-bot").toggleClass('show');//父级
        if ($(".chatbot-bot").hasClass('show')) {
            $(".chataddcont").addClass('show');//图片，文件
        } else {
            $(".chataddcont").removeClass('show');//图片，文件
        }
        $(".chatemojicont").removeClass('show').addClass('hide');//表情
        //allwrap改变padding-bottom值
        $(".allwrap").toggleClass('padmore');
        $('#msg-text').blur();
    })

</script>
<script>
    //发送图片
    function selectedImg() {
        var UIAlbumBrowser = api.require('UIAlbumBrowser');
        UIAlbumBrowser.open({
            max: 1,
            type: "image",
            styles: {
                bg: '#fff',
                mark: {
                    position: 'bottom_left',
                    size: 20
                },
                nav: {
                    bg: 'rgba(0,0,0,0.6)',
                    titleColor: '#fff',
                    titleSize: 18,
                    cancelColor: '#fff',
                    cancelSize: 16,
                    finishColor: '#fff',
                    finishSize: 16
                }
            },
            rotation: true
        }, function (ret) {
            if (ret.eventType === "confirm") {
                if (ret.list[0].size > 1024 * 1024 * 2) {
                    alert("图片大小不能大于2MB");
                    return;
                }
                if (api.systemType === 'ios') {
                    UIAlbumBrowser.transPath({
                        path: ret.list[0].path
                    }, function (ret, err) {
                        sendImage(ret.path);
                    });
                } else {
                    sendImage(ret.list[0].path);
                }
            }
        });
    }

    function sendImage(path) {
        easeChat.sendImage({
            conversationId: conversationId,
            chatType: 'groupChat',
            path: path,
            displayName: path.substring(path.lastIndexOf("/") + 1),
            to: conversationId
        }, function (ret, err) {
            if (ret.status) {
                uploadMsgToCFnet(ret.message);
                addData(false, [ret.message]);
                mui('.mui-scroll-wrapper').scroll().reLayout();
                mui('.mui-scroll-wrapper').scroll().scrollToBottom(100);//100毫秒滚动到底部
            } else {
                sendFail("图片发送失败,请重新发送")
            }
        });
    }

    //发送视频
    function sendVideo(path, name) {
        easeChat.sendVideo({
            conversationId: conversationId,
            chatType: 'groupChat',
            path: path,
            displayName: name,
            to: conversationId
        }, function (ret, err) {
            if (!ret.status) {
                sendFail("视频发送失败,请重新发送");
            } else {
                uploadMsgToCFnet(ret.message);
            }
        });
    }

    function sendFile(path, name) {
        // console.log(name);
        easeChat.sendFile({
            conversationId: conversationId,
            chatType: 'groupChat',
            path: path,
            displayName: name,
            to: conversationId
        }, function (ret, err) {
            if (ret.status) {
                uploadMsgToCFnet(ret.message);
            }
        });
    }

    //发送文件
    function selecteFile() {
        var fileBrowser = api.require('fileBrowser');
        fileBrowser.skin({
            skin: 1
        });
        fileBrowser.open({
            confirm: true
        }, function (ret) {
            if (ret) {
                if (ret.size > 1024 * 1024 * 10) {
                    alert("文件大小不能大于10MB");
                    return;
                }
                var message = {
                    from: myRingName,
                    conversationId: conversationId,
                    icon: "../../image/chat/p03.png",
                    timestamp: new Date().getTime(),
                    isRead: true
                };
                if (ret.name.match('.mp4') || ret.name.match('.rmvb') || ret.name.match('.wmv')) {
                    message.body = {
                        type: "video",
                        displayName: ret.name,
                        localPath: ret.url,
                        remotePath: ""
                    };
                    sendVideo(ret.url, ret.name);
                } else if (ret.name.match('.mp4')) {
                    message.body = {
                        type: "file",
                        displayName: ret.name,
                        localPath: ret.url,
                        remotePath: ""
                    };
                    sendFile(ret.url, ret.name);
                } else {
                    alert('暂不支持此格式文件上传');
                    return;
                }
                addData(false, [message]);
                mui('.mui-scroll-wrapper').scroll().reLayout();
                mui('.mui-scroll-wrapper').scroll().scrollToBottom(100);//100毫秒滚动到底部
            }
        });
    }

    function sendFail(msg) {
        loginRing();
        api.toast({msg: msg});
    }

    function loginRing() {
        easeChat.logout(function (ret, err) {
            easeChat.login({
                username: $api.getStorage('cfRingUsername'),
                password: $api.getStorage('cfRingPassword'),
                autoLogin: true
            }, function (ret, err) {
                if (ret.status) {
                    console.log("登录成功");
                } else {
                    console.log(JSON.stringify(err));
                }
            });
        });
    }

    function parseTag(username) {
        for (var i = 0; i < conversationPeopleList.length; i++) {
            if (username === conversationPeopleList[i].username) {
                return conversationPeopleList[i].identity;
            }
        }
        return [];
    }

    //标记消息已读
    function markMessage() {
        // easeChat.markMessageAsRead({
        //     conversationId: conversationId,
        //     type: 'groupChat',
        //     messageId: messageId
        // }, function (ret, err) {
        //     if (ret.status) {
        //         ringmarkSum++;
        //     }
        // });

        //标记环信已读
        easeChat.markAllMessagesAsRead({
            conversationId: conversationId,
            type: 'groupChat'
        }, function (ret, err) {
            if (ret.status) {
                ringmarkSum += 99999;//为了方便变动
            }
        });
    }

    //上传消息至长风网
    function uploadMsgToCFnet(msg) {
        updateMessage(msg);//更新最后一条消息
        cfnetppPOST(url_ring_updateMsg, {
            msg: msg
        }, false, function (data, err) {
        })
    }

    //改变现显示模式
    function changeUi(type) {
        switch (type) {
            case 'audio':
                $('.chatbtncont .chat-left-key').removeClass('hide').addClass('show');
                $('.chatbtncont .chat-audio').removeClass('show').addClass('hide');
                $('.chatbtncont .chat-right-key').removeClass('show').addClass('hide');
                $('.chat-emoji').removeClass('hide').addClass('show');
                $('#msg-text').hide();
                $('#msg-text').blur();
                $(".chat-input").find(".audioinput").show();
                break;
            case 'text':
                $('.chatbtncont .chat-left-key').removeClass('show').addClass('hide');
                $('.chatbtncont .chat-right-key').removeClass('show').addClass('hide');
                $('.chat-emoji').removeClass('hide').addClass('show');
                $('.chatbtncont .chat-audio').removeClass('hide').addClass('show');
                $('#msg-text').show();
                $('#msg-text').focus();
                $(".chat-input").find(".audioinput").hide();
                break;
        }
        //下面表情列表部分隐藏
        $(".chatbot-bot").removeClass('show');
        $(".chatemojicont").removeClass('show');
        //allwrap改变padding-bottom值
        $(".allwrap").removeClass('padmore');
    }

    function copyToClip(Copytext) {
        cnt = Copytext.replaceAll("<p>", "").replaceAll("</p>", "");
        var imgReg = /<img.*?(?:>|\/>)/gi;
        var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
        var arr = cnt.match(imgReg);
        if (arr != undefined) {
            for (var i = 0; i < arr.length; i++) {
                var imgIndex = cnt.indexOf(arr[i]);
                var src = arr[i].match(srcReg);
                //获取图片地址
                var imgName = src[1].substr(src[1].lastIndexOf("/") + 1);//获取图片名称
                for (var emo in WebIM.Emoji.map) {
                    if (WebIM.Emoji.map[emo] === imgName) {
                        //取出img对应的key
                        cnt = cnt.replace(arr[i], emo);
                        break;
                    }
                }
            }
        }
        var clipBoard = api.require('clipBoard');
        clipBoard.set({
            value: cnt
        }, function (ret, err) {
            api.toast({msg: "内容已复制入剪切板"});
        });
    }
    function openVideo(path) {
        api.openWin({useWKWebView:true,
            name: 'player',
            url: '../player.html',
            slidBackEnabled: false,
            pageParam: {
                path: path
            }
        });
    }
</script>
</body>
</html>